package org.jeecg.modules.charge.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ComUtil;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.entity.charge.ChargeInvoice;
import org.jeecg.entity.charge.ChargeInvoiceInfo;
import org.jeecg.modules.charge.service.impl.ChargeInvoiceInfoServiceImpl;
import org.jeecg.modules.charge.service.impl.ChargeInvoiceServiceImpl;
import org.jeecg.vo.charge.ChargeInvoiceDepositExcel;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
* @Description: 押金
* @Author: jeecg-boot
* @Date:   2019-11-06
* @Version: V1.0
*/
@Slf4j
@Api(tags="押金")
@RestController
@RequestMapping("/b/charge/deposit")
public class ChargeDepositController {
   @Autowired
   private ChargeInvoiceServiceImpl chargeInvoiceService;
    @Autowired
    private ChargeInvoiceInfoServiceImpl chargeInvoiceInfoService;

    /**
     * 押金收费列表
     * @param
     * @param req
     * @return
     */
    @AutoLog(value = "押金收费列表")
    @ApiOperation(value="押金收费列表", notes="押金收费列表")
    @GetMapping(value = "/depositList")
    public Result<Page<ChargeInvoiceInfo>> depositList(ChargeInvoiceInfo chargeInvoiceInfo,
                                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                       HttpServletRequest req) {
        Result<Page<ChargeInvoiceInfo>> result = new Result<Page<ChargeInvoiceInfo>>();
        try{
            Page<ChargeInvoiceInfo> pageList = new Page<ChargeInvoiceInfo>(pageNo,pageSize);
            pageList = chargeInvoiceInfoService.getDepositList(pageList,chargeInvoiceInfo);
            result.setSuccess(true);
            result.setResult(pageList);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return result;
    }
    /**
     * 其他收费作废
     * @return
     */
    @RequestMapping(value = "/deleteBills")
    public Result<ChargeInvoice> deleteBills(@RequestBody ChargeInvoice chargeInvoice) {
        Integer winOrFail = chargeInvoiceInfoService.depositDelete(chargeInvoice);
        if(winOrFail==0){
            return  Result.ok("作废失败");
        }else{
            return  Result.ok("作废成功");
        }
    }

    /**
     * 押金退款
     * @return
     */
    @RequestMapping(value = "/refund")
    public Result<ChargeInvoice> refund(@RequestBody ChargeInvoice chargeInvoice) {
        Integer winOrFail = chargeInvoiceInfoService.depositRefund(chargeInvoice);
        if (winOrFail == 0) {
            return Result.ok("退款失败");
        } else {
            return Result.ok("退款成功");
        }
    }

    /**
     * 押金报表查询
     * @param
     * @param req
     * @return
     */
    @AutoLog(value = "押金报表查询")
    @ApiOperation(value="押金报表查询", notes="押金报表查询")
    @PostMapping(value = "/generaTing")
    public Result<Page<ChargeInvoiceInfo>> generaTing(@RequestBody ChargeInvoiceInfo chargeInvoiceInfo,
                                                         HttpServletRequest req) {
        Result<Page<ChargeInvoiceInfo>> result = new Result<Page<ChargeInvoiceInfo>>();
        try {
            Page<ChargeInvoiceInfo> pageList = new Page<ChargeInvoiceInfo>(chargeInvoiceInfo.getPageNo(),chargeInvoiceInfo.getPageSize());
            pageList = chargeInvoiceInfoService.getDepositReportList(pageList,chargeInvoiceInfo);
            result.setSuccess(true);
            result.setResult(pageList);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param chargeInvoiceInfo
     */
    @AutoLog(value = "押金报表导出")
    @ApiOperation(value="押金报表导出", notes="押金报表导出")
    @PostMapping(value = "/getDepositReport")
    public ModelAndView exportXls(@RequestBody ChargeInvoiceInfo chargeInvoiceInfo) {
        // Step.1 组装查询条件
        LoginUser user = SsoUtil.getLoginUser();
        Page<ChargeInvoiceInfo> pageList = new Page<ChargeInvoiceInfo>(1,Integer.MAX_VALUE);
        pageList = chargeInvoiceInfoService.getDepositReportList(pageList,chargeInvoiceInfo);
        List<ChargeInvoiceDepositExcel> list =  ComUtil.copy(pageList.getRecords(),ChargeInvoiceDepositExcel.class);
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "押金报表导出");
        mv.addObject(NormalExcelConstants.CLASS, ChargeInvoiceDepositExcel.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("押金报表导出", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }
    /*public void getDepositReport(@RequestBody ChargeInvoiceInfo chargeInvoiceInfo, HttpServletResponse response) {
        SimpleDateFormat kpsmf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            XSSFWorkbook book = new XSSFWorkbook();
        try {
            List<ChargeInvoiceInfo> list = chargeInvoiceInfoService.getDepositReportList(chargeInvoiceInfo);
            XSSFSheet sheet = book.createSheet("押金报表");
            String [] vals0 = new String[]{"票据簿编号","票据编号","收费项目","付款人","房间名称","地址","金额","收款方式","收款日期","备注"};
            XSSFCellStyle style = book.createCellStyle();
            //居中
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            //border
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            XSSFRow row = sheet.createRow(0);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, vals0.length-1));
            row.setHeight((short) 0x349);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue("押金报表");
            cell.setCellStyle(style);
            row = sheet.createRow(1);
            for (int i = 0; i < vals0.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(vals0[i]);
                cell.setCellStyle(style);
            }
            if(list != null && list.size()>0){
                Double sum = 0.0;
                for(int i=0;i<list.size();i++){
                    ChargeInvoiceInfo info = list.get(i);
                    String zjSkrq = "";
                    if(info.getZjSkrq() !=null){
                        zjSkrq = kpsmf.format(info.getZjSkrq());
                    }
                    BigDecimal bigDecimal = new BigDecimal(info.getMoney());
                    String out = bigDecimal.toPlainString();
                    sum += info.getMoney();
                    String[] vals2 = {info.getInvoiceDm(),info.getInvoiceHm(),info.getInvoiceObject(),info.getCrmName(),info.getRoomName(),info.getAddress()
                            ,out,info.getPayMethodStr(),zjSkrq,info.getRemarks()};
                    createExcel(sheet, i+2, vals2,style);
                 }
                BigDecimal bigDecimal = new BigDecimal(sum);
                String moneySum = bigDecimal.toPlainString();
                String [] vals3 = new String[]{"合计：","","","","","",moneySum,"","",""};
                createExcel(sheet, list.size()+2, vals3,style);
             }
                 book.write(generateResponseExcel("用户列表",response));
        }catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }*/
    /**
       * @param excelName
       *   要生成的文件名字
       * @return
       * @throws IOException
       */
    private ServletOutputStream generateResponseExcel(String excelName, HttpServletResponse response) throws IOException {
        excelName = excelName == null || "".equals(excelName) ? "excel" : URLEncoder.encode(excelName, "UTF-8");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx");
        return response.getOutputStream();
    }
    private void createExcel(XSSFSheet sheet, int rowNo, String[] vals, XSSFCellStyle style)  {
        if (vals.length > 0) {
            XSSFRow row = sheet.createRow(rowNo);
            for (int i = 0; i < vals.length; i++) {
                String val = vals[i];
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(val);
                cell.setCellStyle(style);
            }
        }
    }
    /**
       * @param excelName
       * double计算保留两位小数
       * @return
       * @throws IOException
       */
    private Double getBigDecimal(Double sum){
        BigDecimal bigsum = new BigDecimal(sum);
        Double sums = bigsum.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return sums;
    }



}
